package cn.fl.system.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cmm.comm.facade.upload.dto.SysUlFilesRecDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.user.facade.system.dto.SysUsrDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.service.ISysUsrService;
import cn.fl.system.utils.FileTypeUtil;
import cn.fl.system.vo.SysUlFilesRecVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lionbridge.activiti.util.FileInfo;
import com.lionbridge.activiti.util.FileUtils;
import fl.constant.facade.framework.constant.UploadConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Description: 文件上传记录表 控制层
 */
@Controller
@RequestMapping("/system/sysulfilesrec")
public class SysUlFilesRecController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(SysUlFilesRecController.class);


    /**
     * SysUlFilesRec 服务层BEAN
     */
    @Autowired
    private ISysUlFilesRecService sysUlFilesRecService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Autowired
    private IUploadApiService uploadApiService;

    @Autowired
    private ISysUsrService sysUsrService;
    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载SysUlFilesRec列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView view = new ModelAndView("system/sysUlFilesRec/sysUlFileRecList");
        return view;
    }

    /**
     * 到上传页面
     */
    @RequestMapping(value = "/toUploadPage.do", method = {RequestMethod.GET})
    public ModelAndView tofile(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "tofile", "加载上传页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView view = new ModelAndView("system/sysUlFilesRec/NewFile");
        return view;
    }

    /**
     * 到测试页面
     */
    @RequestMapping(value = "/tofiletest.do", method = {RequestMethod.GET})
    public ModelAndView tofiletest(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "tofiletest", "加载测试页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView view = new ModelAndView("system/sysUlFilesRec/sysSysUlFilesRecUpload2");
        return view;
    }

    /**
     * 到断点续传测试页面
     */
    @RequestMapping(value = "/toTillFileUploadPage.do", method = {RequestMethod.GET})
    public ModelAndView toTillFileUploadPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toTillFileUploadPage", "加载测试页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView view = new ModelAndView("system/sysUlFilesRec/tillFileUploadDemo");
        return view;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        BaseLogUtils.info(logger, "toModifyPage", "加载SysUlFilesRec Modify页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView view = new ModelAndView("system/sysUlFilesRec/modify");
        view.addObject("id", id);
        return view;
    }

    /**
     * 初始化列表
     */
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger,"initList",this.getRequestParameter(request));
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String pkId = request.getParameter("pkId");
        String tabNm = request.getParameter("tabNm");
        String pkIdList = request.getParameter("pkIdList");//主键List-JL-20170319

        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();
        if ((StringUtils.isEmpty(pkId) && StringUtils.isEmpty(pkIdList))) {
            BaseLogUtils.info(logger, "initList", "查询数据的文件上传信息,数据主键不能为空！PKId:" + JSONObject.toJSONString(pkId), CurrentThreadContext.getCurrentUserName());
            return page;
        }
        //判断此次传参是否为主键List-JL-20170319
        if (StringUtils.isNotEmpty(pkIdList)) {
            pkIdList = pkIdList.substring(1, pkIdList.length() - 1);
            String[] arr = pkIdList.split(", ");
            List<String> pkList = java.util.Arrays.asList(arr);
            qc.setPkIdList(pkList);
        } else {
            qc.setPkId(pkId);
        }
        //2017-4-9 YAOXIURONG 去掉表名查询条件qc.setTabNm(tabNm);
        if (StringUtils.isNotEmpty(tabNm)) {
            qc.setTabNm(tabNm);
        }
        qc.setSysCd(CurrentThreadContext.getCurrentSysCd());//系统代码-必须条件
        page.setCondition(qc);

        BaseLogUtils.info(logger, "initList", "查询数据的文件上传信息.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        List<SysUlFilesRecVO> list = this.sysUlFilesRecService.searchList(qc);

        if (CollectionUtils.isNotEmpty(list)) {
            Map<String, String> audStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapitalConstant.CODE_MATE_AUD_STS_CD);
            Iterator<SysUlFilesRecVO> iterator = list.iterator();
            SysUlFilesRecVO sysUlFilesRecVO = null ;
            //附件信息创建人ID
            List<Long> usrIdList = new ArrayList<>(4);
            while (iterator.hasNext()){
                sysUlFilesRecVO = iterator.next();
                if(!usrIdList.contains(sysUlFilesRecVO.getCrtUsrId())){
                    usrIdList.add(sysUlFilesRecVO.getCrtUsrId());
                }
            }
            //用户ID及NAME MAP
            Map<Long,String> usrIdNmMap = null ;
            if(CollectionUtils.isNotEmpty(usrIdList)){
                usrIdNmMap = new HashMap<>(usrIdList.size());
                SysUsrQueryCondition queryCondition = new SysUsrQueryCondition();
                queryCondition.setUsrIds(usrIdList);
                queryCondition.setSysCd(CurrentThreadContext.getCurrentSysCd());
                queryCondition.setIsValid(1);
                List<SysUsrDTO> sysUsrDTOList = this.sysUsrService.searchSysUsrList(queryCondition);
                if(CollectionUtils.isNotEmpty(sysUsrDTOList)){
                    for(SysUsrDTO dto : sysUsrDTOList){
                        if(usrIdNmMap.containsKey(dto.getId())){
                            continue;
                        }
                        usrIdNmMap.put(dto.getId(),StringUtils.isNotEmpty(dto.getRefRlNm()) ? dto.getRefRlNm() : dto.getUsrNm());
                    }
                }
            }
            if(CollectionUtils.isNotEmpty(list)){
                for (SysUlFilesRecVO vo : list) {
                    if (audStsCdMap != null && audStsCdMap.containsKey(sysUlFilesRecVO.getAudStsCd())) {
                        sysUlFilesRecVO.setAudStsCdNm(audStsCdMap.get(sysUlFilesRecVO.getAudStsCd()));
                    }
                    if(CollectionUtils.isMapNotEmpty(usrIdNmMap) && usrIdNmMap.containsKey(vo.getCrtUsrId())){
                        sysUlFilesRecVO.setCrtUsrRlNm(usrIdNmMap.get(vo.getCrtUsrId()));
                    }
                }
            }
            /*for (SysUlFilesRecVO sysUlFilesRecVO : list) {
                if (audStsCdMap != null && audStsCdMap.containsKey(sysUlFilesRecVO.getAudStsCd())) {
                    sysUlFilesRecVO.setAudStsCdNm(audStsCdMap.get(sysUlFilesRecVO.getAudStsCd()));
                }
                //获取真实名字
	            SysUsrVO usrVO = this.sysUsrService.selectById(sysUlFilesRecVO.getCrtUsrId(), CurrentThreadContext.getCurrentSysCd());
            	if(null != usrVO){
            		sysUlFilesRecVO.setCrtUsrRlNm(usrVO.getRefRlNm());
            	}
            }*/

        }

        page.setResultList(list);
        //page.setEveryPage(Integer.MAX_VALUE);
        page.setTotalCount(list.size());

        //Pager pager = new Pager();//this.sysUlFilesRecService.searchList(page);
        //List<SysUlFilesRecVO> list = (List<SysUlFilesRecVO>) pager.getResultList();
        ListPageVO<SysUlFilesRecVO> listPage = new ListPageVO<SysUlFilesRecVO>(list, list.size());
        return listPage;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeById.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeById", "删除文件上传记录,主键参数为空！", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        List<Long> idsList = new ArrayList<Long>();
        try {
            idsList.add(Long.valueOf(id));
            boolean success = this.sysUlFilesRecService.removeByIds(idsList);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.info(logger, "removeById", "删除文件上传记录失败,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "removeById", "删除文件上传记录成功,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "removeSplById", "删除文件上传记录失败,ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeSplById", "删除文件上传记录失败,系统错误.ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }

        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "getById", "获取文件上传记录,主键参数为空.", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            SysUlFilesRecVO vo = this.sysUlFilesRecService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getById", "获取文件上传记录数据不存在,ID:" + id, CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getById", "获取文件上传记录数据成功,ID:" + id, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "getById", "获取文件上传记录数据失败,ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getById", "获取文件上传记录数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增
     */
    /*@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
    @ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
		try {
			SysUlFilesRecVO entity = new SysUlFilesRecVO();
			//TODO ADD PARAM
			Long id = null;//this.sysUlFilesRecService.add(entity);
			result.setData(id);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("新增失败!");
			logger.error("", ex);
		}

		return result;
	}*/

    /**
     * 修改
     */
    /*@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
    @ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,"修改成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("参数不完整！");
			return result;
		}
		try {
			SysUlFilesRecVO entity = new SysUlFilesRecVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = false;//this.sysUlFilesRecService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("修改失败！");
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("修改失败!");
			logger.error("修改失败!", ex);
		}
		return result;
	}*/

    /**
     * @throws IllegalStateException
     * @throws IOException
     * @Desc 文件上传
     * @Desc 系统相对路径前缀    + 系统代码  + 模块(自定义)  + 时间   + 文件
     */
    @RequestMapping(value = "/upload.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO upload(
            //上传多个文件
            MultipartHttpServletRequest multipartRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Long uploadSign = System.currentTimeMillis();
        String uploadSignStr = uploadSign + "-" + CurrentThreadContext.getCurrentUserName() ;
        BaseLogUtils.info(logger, "upload", "<"+uploadSignStr+">文件上传,上传文件开始.", CurrentThreadContext.getCurrentUserName());
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
        //获取文件 存储位置
        String filePath = request.getParameter("filePath");//前端传过来的文件模块路径
        String sysCd = request.getParameter("sysCd");//系统
        String opTypCd = request.getParameter("opTypCd");//前端传过来的系统类型
        String verNo = request.getParameter("verNo");//版本号
        try {
            Iterator<String> iter = multipartRequest.getFileNames();
            String iterFileName = null;
            if (iter.hasNext()) {
                iterFileName = iter.next();
                // 取得上传文件
                List<MultipartFile> fileList = multipartRequest.getFiles(iterFileName);
                for (MultipartFile f : fileList) {
                    if (f != null) {
                        Map<String, String> map = FileTypeUtil.judgeFileType(f);
                        if (!"200".equals(map.get("code"))) {
                            result.setSuccess(BaseConstant.IS_YESNO_NO);
                            result.setInfo(map.get("info"));
                            return result;
                        }
                    }
                }
            }
            String rootPath = PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH);
            if (filePath.contains(rootPath)) {//防止前端写了IP地址
                filePath = filePath.replace(rootPath, "");
            }
            BaseLogUtils.info(logger, "upload", "<"+uploadSignStr+">文件上传A,上传文件路径["+filePath+"],当前耗时："+(System.currentTimeMillis() - uploadSign)+"/ms", CurrentThreadContext.getCurrentUserName());
            net.sf.json.JSONArray fileParams = this.sysUlFilesRecService.fileUpload(filePath, multipartRequest,uploadSignStr);
            BaseLogUtils.info(logger, "upload", "<"+uploadSignStr+">文件上传A,上传文件fileParams:["+(null != fileParams ? JSON.toJSONString(fileParams) : "is null")+"],当前耗时："+(System.currentTimeMillis() - uploadSign)+"/ms", CurrentThreadContext.getCurrentUserName());
            result.setData(fileParams);
            result.setInfo(SysLogConstant.LOG_FILE_UPLOAD_SUCC);
            result.setSuccess(BaseConstant.IS_YESNO_YES);
            //生成ios plist
            BaseLogUtils.info(logger, "upload", "<"+uploadSignStr+">文件上传A,上传文件opTypCd:["+opTypCd+"],当前耗时："+(System.currentTimeMillis() - uploadSign)+"/ms", CurrentThreadContext.getCurrentUserName());
            if ("1".equals(opTypCd)) {
                String root = PropertiesCacheUtils.getProperty("ulfiles.ulfiles.properties.root.path");
                String costomer = PropertiesCacheUtils.getProperty("ulfiles.ulfiles.properties.costomer.path");
                //获取ios安装包路径
                String servePath = fileParams.getJSONObject(0).getString("filePath");
                //读取文件内容并修改
                String url = root + costomer + "app/Lionbridge.plist";
                //读取原始plist模板内容
                BaseLogUtils.info(logger, "upload", "<"+uploadSignStr+">文件上传A,上传文件read开始:["+opTypCd+"],当前耗时："+(System.currentTimeMillis() - uploadSign)+"/ms", CurrentThreadContext.getCurrentUserName());
                String content = this.read(url, servePath, verNo, sysCd);
                BaseLogUtils.info(logger, "upload", "<"+uploadSignStr+">文件上传A,上传文件read结束content:["+content+"],当前耗时："+(System.currentTimeMillis() - uploadSign)+"/ms", CurrentThreadContext.getCurrentUserName());
                //根据原始plist模板文件重新生成新的plist文件防止缓存出现
                String newurl = url.substring(0, url.lastIndexOf("/")) + servePath.substring(servePath.lastIndexOf
                        ("/"), servePath.lastIndexOf(".ipa")) + ".plist";
                //将修改后的文件内容重新写入文件
                this.write(newurl, content);
                BaseLogUtils.info(logger, "upload", "<"+uploadSignStr+">文件上传A,上传文件结束,当前耗时："+(System.currentTimeMillis() - uploadSign)+"/ms", CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "upload", "<"+uploadSignStr+">文件上传成功.FILEPATH:" + filePath + ".FILEPARAMS:" + fileParams+",当前耗时："+(System.currentTimeMillis() - uploadSign)+"/ms", CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "upload", "<"+uploadSignStr+">文件上传失败.FILEPATH:" + filePath + ".ERROR", CurrentThreadContext.getCurrentUserName(), ex);
        } catch (IllegalStateException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "upload", "<"+uploadSignStr+">文件上传失败,系统错误.FILEPATH:" + filePath + ".ERROR", CurrentThreadContext.getCurrentUserName(), ex);
        }
        BaseLogUtils.info(logger, "upload", "<"+uploadSignStr+">文件上传结束.返回参数result["+JSON.toJSONString(result)+"],当前耗时："+(System.currentTimeMillis() - uploadSign)+"/ms", CurrentThreadContext.getCurrentUserName());
        return result;

    }

    @RequestMapping("/downLoad.do")
    public ModelAndView downLoad(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_DOWNLOAD_SUCC);

        String fileName = "";//request.getParameter("fileName");
        String filePath = "";//request.getParameter("filePath");
        String id  = request.getParameter("id");//如果有ID则使用ID获取DB数据获取内容下载
        if(StringUtils.isEmpty(id)){
            BaseLogUtils.info(logger, "downLoad", "下载附件ID不能为空!");
            return null;
        }
        try {
            String rootPath = PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH);
            if (filePath.contains(rootPath)) {
                filePath = filePath.replace(rootPath, "");
            }
            this.sysUlFilesRecService.fileDownload(id, fileName, filePath, request, response);
            BaseLogUtils.info(logger, "downLoad", "文件下载成功.FILENAME:" + fileName + ".FILEPATH:" + filePath, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "downLoad", "文件下载失败.FILENAME:" + fileName + ".FILEPATH:" + filePath + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("文件下载失败!");
            BaseLogUtils.error(logger, "downLoad", "文件下载失败,系统错误.FILENAME:" + fileName + ".FILEPATH:" + filePath + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return null;
    }

    /**
     * 获取服务器路径前缀
     */
    @RequestMapping(value = "/getServerPath.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getServerPath(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String serverPrefixPath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_SERVER_PATH);
        return serverPrefixPath;
    }

    /*
     * 打包下载
     */
    @RequestMapping(value = "/zipDownload.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView zipDownload(HttpServletRequest request, HttpServletResponse response) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String tmpZipFileName = uuid + ".zip";//临时名称
        //String rootPath = "D://";
        String rootPath = PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH);

        try {
            byte[] buffer = new byte[1024];
            ZipOutputStream out = new ZipOutputStream(response.getOutputStream());

            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-Disposition", "attachment; filename=" + tmpZipFileName);
            request.setCharacterEncoding("UTF-8");

//            String data = "[{\"name\":\"测试.png\",\"path\":\"attachments/x1.png\"},{\"name\":\"测.png\"," +
//                    "\"path\":\"attachments/x2.png\"},{\"name\":\"测试.png\",\"path\":\"attachments/x3.png\"},{\"name" +
//                    "\":\"测.png\",\"path\":\"attachments/x2.png\"},{\"name\":\"测试.png\",\"path\":\"attachments/x1.png\"}]";
            String data = request.getParameter("files");
            if (StringUtils.isEmpty(data)) {
                data = "[]";
            }
            JSONArray jsonArray = JSONArray.parseArray(data);
            List<String> list = new ArrayList<String>();
            Map<String, Integer> map = new HashMap<String, Integer>();
            for (Object object : jsonArray) {
                JSONObject obj = (JSONObject) object;
                String fileName = obj.getString("name");
                String filePath = obj.getString("path");
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(rootPath + filePath);
                    if (list.contains(fileName)) {
                        map.put(fileName, map.get(fileName) + 1);
                        fileName = fileName.replace(".", "(" + map.get(fileName) + ").");
                    } else {
                        map.put(fileName, 0);
                    }
                    out.putNextEntry(new ZipEntry(fileName));
                    //下载的文件名写入list
                    list.add(fileName);
                    int bytesRead;
                    while (-1 != (bytesRead = fis.read(buffer, 0, buffer.length))) {
                        out.write(buffer, 0, bytesRead);
                    }
                } catch (Exception e) {
                    BaseLogUtils.error(logger, "batchDownload", "下载打包文件循环中失败!" + obj.toJSONString(), e);
                } finally {
                    if (null != out) {
                        out.flush();
                        out.closeEntry();
                    }
                    if (null != fis) {
                        fis.close();
                        fis = null;
                    }
                }
            }
            if (null != out) {
                out.finish();
                out.close();
                out = null;
            }
        } catch (Exception e) {
            BaseLogUtils.error(logger, "batchDownload", "下载打包文件失败!", e);
        }
        return null;
    }

    /*
     * 打包下载
     */
    @RequestMapping(value = "/zipDownloadById.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView zipDownloadById(HttpServletRequest request, HttpServletResponse response) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String tmpZipFileName = uuid + ".zip";//临时名称
        try {
            byte[] buffer = new byte[1024];
            ZipOutputStream out = new ZipOutputStream(response.getOutputStream());

            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-Disposition", "attachment; filename=" + tmpZipFileName);
            request.setCharacterEncoding("UTF-8");

//            String data = "[170102164002161,170102164002164]";
            String data = request.getParameter("ids");
            BaseLogUtils.newWebLogger("打包下载入参,data:" + JSON.toJSONString(data)).info();
            if (StringUtils.isEmpty(data)) {
                data = "[]";
            }
            JSONArray jsonArray = JSONArray.parseArray(data);
            SysUlFilesRecQueryCondition condition = new SysUlFilesRecQueryCondition();
            List<String> ids = JSONObject.parseArray(data, String.class);
            condition.setIdList(ids);
            condition.setSysCd(CurrentThreadContext.getFlServiceSysCd());
            BaseLogUtils.newWebLogger("打包下载查询附件信息入参,condition:" + JSON.toJSONString(condition)).info();
            List<SysUlFilesRecDTO> sysUlFilesRecDTOS = this.uploadApiService.searchSysUlFilesRecList(condition);
            BaseLogUtils.newWebLogger("打包下载查询附件信息结果,sysUlFilesRecDTOS:" + JSON.toJSONString(sysUlFilesRecDTOS)).info();
            Map<String, SysUlFilesRecDTO> SysUlFilesRecMap = new HashMap<String, SysUlFilesRecDTO>();
            for (SysUlFilesRecDTO sysUlFilesRecDTO: sysUlFilesRecDTOS) {
                SysUlFilesRecMap.put(sysUlFilesRecDTO.getId() + "", sysUlFilesRecDTO);
            }
            List<String> list = new ArrayList<String>();
            Map<String, Integer> map = new HashMap<String, Integer>();
            for (int i = 0; i < jsonArray.size(); i++) {
                String id = jsonArray.getString(i);
                SysUlFilesRecDTO sysUlFilesRecDTO = SysUlFilesRecMap.get(id);
                String fileName = sysUlFilesRecDTO.getDatNm() != null ? sysUlFilesRecDTO.getDatNm() : sysUlFilesRecDTO.getFileNm();
                String filePath = sysUlFilesRecDTO.getFilePath();
                fileName = fileName + filePath.substring(filePath.lastIndexOf("."));
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(sysUlFilesRecDTO.getAbsLocPath());
                    if (list.contains(fileName)) {
                        map.put(fileName, map.get(fileName) + 1);
                        fileName = fileName.replace(".", "(" + map.get(fileName) + ").");
                    } else {
                        map.put(fileName, 0);
                    }
                    out.putNextEntry(new ZipEntry(fileName));
                    //下载的文件名写入list
                    list.add(fileName);
                    int bytesRead;
                    while (-1 != (bytesRead = fis.read(buffer, 0, buffer.length))) {
                        out.write(buffer, 0, bytesRead);
                    }
                } catch (Exception e) {
                    BaseLogUtils.newLogger("下载打包文件循环中失败!id=" + id + ".ERROR:" + e.getMessage()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
                } finally {
                    if (null != out) {
                        out.flush();
                        out.closeEntry();
                    }
                    if (null != fis) {
                        fis.close();
                        fis = null;
                    }
                }
            }
            if (null != out) {
                out.finish();
                out.close();
                out = null;
            }
        } catch (Exception e) {
            BaseLogUtils.newLogger("下载打包文件失败!" + ".ERROR:" + e.getMessage()).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
        }
        return null;
    }

    // 大文件上传
    @RequestMapping(value = "tillFileUpload.do", method = RequestMethod.POST)
    @ResponseBody
    public DataResultVO tillFileUpload(HttpServletRequest request, HttpServletResponse response,
                                       //上传多个文件
                                       MultipartHttpServletRequest multipartRequest) throws Exception {
        BaseLogUtils.info(logger, "tillFileUpload", "请求参数："+ this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
        Iterator<String> iter = multipartRequest.getFileNames();//获取单个文件
        String iterFileName = null;
        if (!iter.hasNext()) {// 如果没有文件提示
            BaseLogUtils.info(logger, "tillFileUpload", "文件上传失败,未选中文件内容.", CurrentThreadContext.getCurrentUserName());
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("请选择要上传的文件!");
            return result;
        } else {
            iterFileName = iter.next();
            // 取得上传文件
            List<MultipartFile> fileList = multipartRequest.getFiles(iterFileName);
            for (MultipartFile f : fileList) {
                if (f != null) {
                    Map<String, String> map = FileTypeUtil.judgeFileType(f);
                    if (!"200".equals(map.get("code"))) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo(map.get("info"));
                        return result;
                    }
                }
            }
        }
        MultipartFile file = null;// 创建返回的集合
        while (iter.hasNext()) {
            BaseLogUtils.info(logger, "tillFileUpload", "文件上传获取MultipartFile文件!", CurrentThreadContext.getCurrentUserName());
            List<MultipartFile> fileList = multipartRequest.getFiles(iter.next());// 取得上传文件
            for (MultipartFile f : fileList) {
                file = f;
                break;
            }
        }
        String filePath = request.getParameter("filePath");//模块路径
        String chunks = request.getParameter("chunks");
        String chunk = request.getParameter("chunk");
        //String name = request.getParameter("name");
        Long userId = CurrentThreadContext.getCurrentUserId();
        String fileName = request.getParameter("fileName");
        String md5 = request.getParameter("md5");
        String lastModifiedDate = request.getParameter("lastModifiedDate");//Thu Apr 13 2017 18:37:18 GMT+0800 (中国标准时间)
        String originFileName = request.getParameter("originFileName");
        String type = request.getParameter("type");
        String ext = request.getParameter("ext");
        String size = request.getParameter("size");

        FileInfo info = new FileInfo();
        if(StringUtils.isNotEmpty(chunks)){
            info.setChunks(Integer.valueOf(chunks));
        }
        if(StringUtils.isNotEmpty(chunk)){
            info.setChunk(Integer.valueOf(chunk));
        }
        info.setUserId(String.valueOf(userId));
        info.setFileName(fileName);
        info.setMd5(md5);
        info.setLastModifiedDate(lastModifiedDate);
        info.setOriginFileName(originFileName);
        info.setType(type);
        info.setExt(ext);
        info.setSize(size);

        if (file != null && !file.isEmpty()) { // 验证请求不会包含数据上传，所以避免NullPoint这里要检查一下file变量是否为null
            StringBuffer savePath = null;
            if(info.getChunks() <= 0){//不需要分片直接指定上传
                savePath = getTillFileUploadPath(filePath, false, null);// 拼接存入路径->系统相对路径前缀 + 系统代码 + 模块(自定义) + 时间 + 文件
            }else{//需要分片, 第三个参数使用默认值tillFilePCTmp
                savePath = getTillFileUploadPath(filePath, true, null);// 拼接存入路径->系统相对路径前缀 + 系统代码 + 模块(自定义) + 固定路径 + 文件
            }
            try {
                File target = FileUtils.getReadySpace(info, savePath.toString()); // 为上传的文件准备好对应的位置
                if (target == null) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("创建文件路径出错!");
                    BaseLogUtils.info(logger, "tillFileUpload", "创建文件路径出错!"+JSON.toJSONString(info), CurrentThreadContext.getCurrentUserName());
                    return result;
                }
                file.transferTo(target); // 保存上传文件
                if(info.getChunks() <= 0){
                    //不需要分片保存数据库
                    //DbUtils.update("insert into own_upload (origin_file_name,file_name,access_path) values(?,?,?)",new Object[]{info.getOriginFileName(),target.getName(),Constant.ACCESS_ROOT_PATH+"/"+target.getName()});
                    JSONArray fileParams = new JSONArray();
                    JSONObject fileParam = new JSONObject();
                    String prifixPath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH);// 根目录
                    fileParam.put("fileNm", originFileName);
                    String serverPath =savePath.toString().replace(prifixPath, "")+fileName+"."+ext;
                    fileParam.put("filePath", serverPath);
                    fileParams.add(fileParam);
                    result.setData(fileParams);
                }
                result.setSuccess(BaseConstant.IS_YESNO_YES);
                return result;
            } catch (IOException e) {
                BaseLogUtils.error(logger, "tillFileUpload", "数据上传失败!"+JSON.toJSONString(info), CurrentThreadContext.getCurrentUserName(), e);
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("数据上传失败!");
                return result;
            }
        }
        BaseLogUtils.error(logger, "tillFileUpload", "上传请求参数不完整!"+JSON.toJSONString(info), CurrentThreadContext.getCurrentUserName());
        result.setSuccess(BaseConstant.IS_YESNO_NO);
        result.setInfo("上传请求参数不完整!");
        return result;
    }

    // 大文件上传
    @RequestMapping(value = "tillFileUploadStatus.do", method = RequestMethod.POST)
    @ResponseBody
    public DataResultVO tillFileUploadStatus(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "tillFileUploadStatus", "请求参数："+ this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
        String status = request.getParameter("status");
        String originFileName = request.getParameter("originFileName");
        String fileName = request.getParameter("fileName");
        String chunkIndex = request.getParameter("chunkIndex");
        String size = request.getParameter("size");

        String chunks = request.getParameter("chunks");
        String ext = request.getParameter("ext");
        String md5 = request.getParameter("md5");

        String filePath = request.getParameter("filePath");

        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
        if (StringUtils.isEmpty(status)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("分块验证状态不能为空!");
            BaseLogUtils.info(logger, "tillFileUploadStatus", "分块验证状态不能为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        FileInfo info = new FileInfo();
        info.setOriginFileName(originFileName);
        info.setFileName(fileName);
        if(StringUtils.isNotEmpty(chunkIndex)){
            info.setChunkIndex(Integer.valueOf(chunkIndex));
        }
        info.setSize(size);
        if(StringUtils.isNotEmpty(chunks)){
            info.setChunks(Integer.valueOf(chunks));
        }
        info.setExt(ext);
        info.setMd5(md5);

        if (StringUtils.isNotBlank(status)) {
            StringBuffer savePath = null;
            if (status.equals("chunkCheck")) { // 分块验证
                savePath = getTillFileUploadPath(filePath, true, null);//分片验证:系统相对路径前缀 + 系统代码 + 模块(自定义) + 固定 + 文件
                // 检查目标分片是否存在且完整
                if (FileUtils.chunkCheck(savePath.toString() + info.getFileName() + "/" + info.getChunkIndex(),
                        Long.valueOf(info.getSize()))) {
                    result.setSuccess(BaseConstant.IS_YESNO_YES);
                    return result;
                } else {
                    result.setSuccess(2);//分片不完整不需要处理
                    return result;
                }
            } else if (status.equals("chunksMerge")) { // 分块合并
                savePath = getTillFileUploadPath(filePath, false, null);// 拼接存入路径->系统相对路径前缀 + 系统代码 + 模块(自定义) + 时间 + 文件
                StringBuffer tmpPath = getTillFileUploadPath(filePath, true, null);//分片验证:系统相对路径前缀 + 系统代码 + 模块(自定义) + 固定 + 文件;
                String epath = FileUtils.chunksMerge(info.getFileName(), info.getExt(), info.getChunks(), info.getMd5(),
                        tmpPath.toString(), savePath.toString());
                if (epath == null) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("合并文件文件出错!");
                    return result;
                }
                //插入数据库
                // TODO DbUtils.update("insert into own_upload (origin_file_name,file_name,access_path) values(?,?,?)",new Object[]{info.getOriginFileName(),path,Constant.ACCESS_ROOT_PATH+"/"+path});
                result.setSuccess(BaseConstant.IS_YESNO_YES);
                result.setInfo("操作成功!");
                JSONArray fileParams = new JSONArray();
                JSONObject fileParam = new JSONObject();
                String prifixPath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH);// 根目录
                fileParam.put("fileNm", originFileName);
                String serverPath = savePath.toString().replace(prifixPath, "") + epath;
                fileParam.put("filePath", serverPath);
                fileParams.add(fileParam);
                result.setData(fileParams);
                return result;
            }
        }
        BaseLogUtils.info(logger, "tillFileUploadStatus", "请求参数不完整!"+ this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
        result.setSuccess(BaseConstant.IS_YESNO_NO);
        result.setInfo("请求参数不完整!");
        return result;
    }

    //**********************************************私有方法*******************************************//

    /**
     * 获取断点续传文件路径
     * @param filePath 模块路径
     * @param isReplaceTimePath 是否要替换时间路径
     * @param replacePath 要替换时间路径的值 例如：  tillFilePCTmp,  默认值：tillFilePCTmp
     * @return
     */
    private StringBuffer getTillFileUploadPath(String filePath, boolean isReplaceTimePath, String replacePath) {
        String prifixPath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH);// 根目录
        StringBuffer savePath = new StringBuffer(prifixPath);// 最终保存路径
        if (!savePath.toString().endsWith(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH)) {// 判断是否以"/"结尾,不是加入斜杠
            savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
        }
        savePath.append(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_COSTOMER_PATH));// 自定义代码-其中包括系统代码
        if (StringUtils.isNotEmpty(filePath)) {// 如果不等于空则加入
            if (filePath.startsWith(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH)) {// 判断是否以"/"开头
                savePath.append(filePath.substring(1));
            } else {
                savePath.append(filePath);
            }

        }
        BaseLogUtils.info(logger, "upload", "文件上传B2", CurrentThreadContext.getCurrentUserName());
        if (!savePath.toString().endsWith(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH)) {// 判断是否以"/"结尾
            savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
        }
        if(isReplaceTimePath){
            if(StringUtils.isEmpty(replacePath)){
                replacePath = "tillFilePCTmp";
            }
            savePath.append(replacePath);
            savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
        }else{
            String currentTime = DateUtils.formatDateToString(new Date(), DateUtils.YYYYMMDD);
            savePath.append(currentTime);
            savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
        }
        return savePath;
    }

    /**
     * 读取文件
     *
     * @param filePath
     * @return
     */
    private String read(String filePath, String ipa, String verNo, String sysCd) {
        String text = "";
        String dire = "";
        if ("11002".equals(sysCd)) {
            text = "狮桥助手";
            dire = "sqhelper";
        } else if ("11003".equals(sysCd)) {
            text = "狮桥在线";
            dire = "sqonline";
        } else if ("11004".equals(sysCd)) {
            text = "狮桥汽车";
            dire = "sqcar";
        } else if ("11005".equals(sysCd)) {
            text = "狮桥商家";
            dire = "sqshop";
        } else if ("11006".equals(sysCd)) {
            text = "狮桥助手管理版";
            dire = "sqhelpermgt";
        }
        BufferedReader br = null;
        String line = null;
        StringBuffer buf = new StringBuffer();

        try {
            // 根据文件路径创建缓冲输入流
            br = new BufferedReader(new FileReader(filePath));
            int i = 1;
            // 循环读取文件的每一行, 对需要修改的行进行修改, 放入缓冲对象中
            while ((line = br.readLine()) != null) {
                if (i == 14) {
                    line = line.substring(0, line.indexOf(".com/") + 5) + ipa + "</string>";
                } else if (i == 22) {
                    line = line.substring(0, line.indexOf("sqcar")) + dire + "/icon@2x.png</string>";
                } else if (i == 30) {
                    line = line.substring(0, line.indexOf("sqcar")) + dire + "/icon@3x.png</string>";
                } else if (i == 38) {
                    line = line.substring(0, line.indexOf("<string>") + 8) + verNo + "</string>";
                } else if (i == 42) {
                    line = line.substring(0, line.indexOf("<string>") + 8) + text + "</string>";
                }
                buf.append(line);
                buf.append(System.getProperty("line.separator"));
                i++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                }
            }
        }
        return buf.toString();
    }

    /**
     * 写入内容
     *
     * @param filePath
     * @param content
     */
    private void write(String filePath, String content) {
        BufferedWriter bw = null;
        try {
            // 根据文件路径创建缓冲输出流
            bw = new BufferedWriter(new FileWriter(filePath));
            // 将内容写入文件中
            bw.write(content);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    bw = null;
                }
            }
        }
    }
    /**
     * post用base64传文件  最好一个一个传
     * @param request
     * @param response
     * @return
     * 2018年5月28日
     * lxb
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/uploadPhoto.do", method = { RequestMethod.POST})
    @ResponseBody
    public DataResultVO uploadPhoto(HttpServletRequest request, HttpServletResponse response) {
        String fileParams = request.getParameter("fileParams");//文件资料
        String filePath = request.getParameter("filePath");//
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        if(StringUtils.isEmpty(fileParams)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "saveUpload", "修改数据,主键不存在.[fileParams="+fileParams+"]", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        try {

            if(StringUtils.isNotBlank(fileParams)){
                //上传文件
                List<Map> list= JSON.parseArray(fileParams,Map.class);
                if (list!=null&&list.size()>0) {
                    net.sf.json.JSONArray params= this.sysUlFilesRecService.fileUploadB64(filePath, list);
                    result.setData(params);
                    result.setInfo(SysLogConstant.LOG_FILE_UPLOAD_SUCC);
                    result.setSuccess(BaseConstant.IS_YESNO_YES);
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(e.getMessage());
            BaseLogUtils.info(logger, "uploadPhoto", "失败.[id="+fileParams+"] DATA:" +  e.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }
}